package cn.fjy.android.phone.service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.util.Log;
import cn.fjy.android.phone.receiver.PhoneStateReceiver;
import cn.fjy.android.phone.worker.Recorder;
import cn.fjy.android.phone.worker.TalkTimeRemind;
import cn.fjy.android.res.Constant;
import cn.fjy.android.utils.APPSession;

/**
 * @author GrayF 2011-5-28
 * @version 1.0
 */
public class PhoneStateService extends Service {

	private final static String tag = "PhoneStateService";

	private boolean isCreated = false;

	@Override
	public void onCreate() {
		Log.i(tag, "服务启动");
		init();
		isCreated = true;
		super.onCreate();
	}

	private void init() {
		class CallOutReceiver extends BroadcastReceiver {
			@Override
			public void onReceive(Context context, Intent intent) {
				TelephonyManager telManager = (TelephonyManager) context
						.getSystemService(Context.TELEPHONY_SERVICE);
				Vibrator mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
				SharedPreferences pre = getSharedPreferences(
						Constant.CONFIG_FILE_NAME, MODE_PRIVATE);
				new Thread(new CallOutListener(mVibrator, telManager, pre))
						.start();
			}

		}
		registerReceiver(new CallOutReceiver(), new IntentFilter(
				"android.intent.action.NEW_OUTGOING_CALL"));
		registerReceiver(new PhoneStateReceiver(), new IntentFilter(
				"android.intent.action.PHONE_STATE"));
	}

	@Override
	public void onDestroy() {
		// Log.i(tag, "onDestroy");
		super.onDestroy();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		Log.i(tag, "onStart");
		if (!isCreated) {
			init();
		}
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// Log.i(tag, "onBind");
		return null;
	}

}

class CallOutListener implements Runnable {

	// 振动器
	Vibrator mVibrator;
	// 电话服务
	TelephonyManager telManager;

	SharedPreferences mSharePre;

	public CallOutListener(Vibrator mVibrator, TelephonyManager telManager,
			SharedPreferences mSharePre) {
		this.mVibrator = mVibrator;
		this.telManager = telManager;
		this.mSharePre = mSharePre;
	}

	@Override
	public void run() {
		// 获取当前话机状态
		Log.i("PhoneStateService", "开始.........."
				+ Thread.currentThread().getName());
		// 记录拨号开始时间
		long threadStart = System.currentTimeMillis();
		Process process;
		InputStream inputstream;
		BufferedReader bufferedreader;
		try {
			process = Runtime.getRuntime().exec("logcat -v time -b radio");
			inputstream = process.getInputStream();
			InputStreamReader inputstreamreader = new InputStreamReader(
					inputstream);
			bufferedreader = new BufferedReader(inputstreamreader);
			String str = "";
			long dialingStart = 0;
			boolean enableVibrator = false;
			boolean isAlert = false;
			boolean vibratored = false;
			TalkTimeRemind mRemind = new TalkTimeRemind(
					mVibrator,
					mSharePre.getInt(Constant.PROP_KEY_TALKTIME_REMIND_TYPE, 1),
					telManager);
			while ((str = bufferedreader.readLine()) != null) {
				// Log.i("PhoneStateService",
				// "话机状态:"+telManager.getCallState());
				// 如果话机状态从摘机变为空闲,销毁线程

				if (telManager.getCallState() == TelephonyManager.CALL_STATE_IDLE) {
					Log.i("PhoneStateService", "挂机");
					mRemind.setEnable(false);
					break;
				}

				if (vibratored) {
					continue;
				}

				// 线程运行5分钟自动销毁
				if (System.currentTimeMillis() - threadStart > 300000
						&& !vibratored) {
					break;
				}
				// Log.i("TestService", Thread.currentThread().getName() + ":"
				// + str);
				// 记录GSM状态DIALING

				if (str.contains("GET_CURRENT_CALLS")
						&& str.contains("DIALING")) {
					// 当DIALING开始并且已经经过ALERTING或者首次DIALING
					if (!isAlert || dialingStart == 0) {
						// 记录DIALING状态产生时间
						dialingStart = System.currentTimeMillis();
						isAlert = false;
					}
					continue;
				}
				if (str.contains("GET_CURRENT_CALLS")
						&& str.contains("ALERTING") && !enableVibrator) {

					long temp = System.currentTimeMillis() - dialingStart;
					isAlert = true;
					// 这个是关键,当第一次DIALING状态的时间,与当前的ALERTING间隔时间在1.5秒以上并且在20秒以内的话
					// 那么认为下次的ACTIVE状态为通话接通.
					if (temp > 1500 && temp < 20000) {
						enableVibrator = true;
						Log.i("PhoneStateService", "间隔时间....." + temp + "....."
								+ Thread.currentThread().getName());
					}
					continue;
				}
				if (str.contains("GET_CURRENT_CALLS") && str.contains("ACTIVE")
						&& enableVibrator) {
					if (mSharePre.getBoolean(
							Constant.PROP_KEY_CALL_ON_VIBRATOR, false)) {
						// 接通震动
						mVibrator.vibrate(mSharePre.getInt(
								Constant.PROP_KEY_VIBRATOR_TIME, 100));
					}
					if (mSharePre.getBoolean(Constant.PROP_KEY_TALKTIME_REMIND,
							false)) {
						// 通话提醒
						mRemind.setEnable(true);
						new Thread(mRemind).start();
					}
					// 通话录音
					if (mSharePre.getBoolean(Constant.PROP_KEY_RECORD_OUT,
							false)) {
						Recorder recorder = new Recorder(
								System.currentTimeMillis() + "");
						APPSession.setValue(Constant.SESSION_KEY_RECORD,
								recorder);
						new Thread(recorder).start();
					}
					enableVibrator = false;
					vibratored = true;
				}
			}
			Log.i("PhoneStateService", "结束.........."
					+ Thread.currentThread().getName());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
